//
//  BJYDownloadingVC.m
//  JW_BasePorject
//
//  Created by JW on 2018/7/2.
//  Copyright © 2018年 JW. All rights reserved.
//

#import "BJYDownloadingVC.h"

#import "BJYDownlodingCell.h"

#import <BJPlayerManagerCore/BJPlayerManagerCore.h>
#import <BJPlayerManagerUI/MBProgressHUD+bjp.h>

#import "PMDownloadModel+ZYVideo.h"

@interface BJYDownloadingVC ()<UITableViewDelegate,UITableViewDataSource,PMDownloadDelegate>

@property (nonatomic, strong)UITableView *downloadingTab;

@property (nonatomic, strong)NSMutableArray *dataArray;


@end

@implementation BJYDownloadingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"正在缓存";
    
    [self.view addSubview:self.downloadingTab];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [PMDownloadManager downloadManager].delegate = self;
    [self.downloadingTab reloadData];
    
}

- (void)initData{
    if([[PMDownloadManager downloadManager].downloadingList count]) {
        self.dataArray = [NSMutableArray arrayWithArray:[PMDownloadManager downloadManager].downloadingList];
    }
    [self.downloadingTab reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BJYDownlodingCell *cell = [BJYDownlodingCell cellWithTableView:tableView];
    cell.PM_model = self.dataArray[indexPath.row];
    
    return cell;
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

#pragma mark - PMDownloadDelegate
- (void)startDownload:(PMDownloader *)downloader {
    NSLog(@"TableView: %s", __func__);
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD bjp_closeLoadingView:self.view];
    });
    
    [self performSelectorOnMainThread:@selector(initData) withObject:nil waitUntilDone:YES];
}

- (void)updateProgress:(PMDownloader *)downloader {
    //    NSLog(@"TableView: %s", __func__);
    [self performSelectorOnMainThread:@selector(updateDownloadCell:) withObject:downloader waitUntilDone:YES];
}

- (void)finishedDownload:(PMDownloader *)downloader {
    //    NSLog(@"TableView: %s", __func__);
    [self performSelectorOnMainThread:@selector(finishedUpdateDownloadCell:) withObject:downloader waitUntilDone:YES];
}

- (void)downloadFail:(nullable PMDownloader *)downloader beforeDownloadError:(nullable PMBeforeDownloadModel *)beforeDownloadModel {
    
    //    !!!:对于已经加入下载的任务,resume的时候如果发生了下载前的token错误是需要调用resetDownloadWithDownloader...方法的
    //下载前的错误信息:下载前主要是会检测一下传入的token参数是否能获取到正确的url,如果不能会抛出错误
    //下载前会检测token,这里可能会需要时间检测,建议此处加上loading
    //    !!!:PMDownloadURLCheckState_Checking表示检测中,PMDownloadURLCheckState_Complete表示检测完\
    //    检测完,如果有error, 也会在beforeDownloadModel.error中包含,
    NSError *error = beforeDownloadModel.error;
    BJPMErrorCode errorCode = error.code;
    if(beforeDownloadModel) {
        if(beforeDownloadModel.urlCheckState == PMDownloadURLCheckState_Checking) {//表示正在检测中
            //ui thred loading
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD bjp_showLoading:@"" toView:self.view];
            });
            return;
        }
        else if (beforeDownloadModel.urlCheckState == PMDownloadURLCheckState_Complete) {//表示检测完
            if(errorCode == BJPMErrorCodeDownloadInvalid) {
                //TODO:下载的URL失效时,上层需要传一个新的token.Demo此处暂不处理,需客户自己提供
                //        !!!:此处token需要客户获取一个新的token,test12345678仅供内部测试使用
                
                
                //1-可以给提示要重传token
                //                dispatch_async(dispatch_get_main_queue(), ^{
                //                    [MBProgressHUD bjp_showMessageThenHide:@"重传token" toView:self.view onHide:nil];
                //                });
#pragma mark - 重置token
                //或者直接重新设置token
                [[PMDownloadManager downloadManager] resetDownloadWithDownloader:downloader token:@"test12345678"];
            }
            else {
                // ui thread  remove loading
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD bjp_closeLoadingView:self.view];
                });
            }
        }
        else {//下载前的其他错误
            // ui thread  remove loading
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *errMsg = [error.userInfo objectForKey:NSLocalizedDescriptionKey] ?: @"";
                NSString *msg = [NSString stringWithFormat:@"错误码:%td \n %@", error.code, errMsg];
                [MBProgressHUD bjp_showMessageThenHide:msg toView:self.view onHide:nil];
                
                NSArray *cellArr = [self.downloadingTab visibleCells];
                for (id obj in cellArr) {
                    if([obj isKindOfClass:[BJYDownlodingCell class]]) {
                        BJYDownlodingCell *cell = (BJYDownlodingCell *)obj;
#pragma mark - 设置cell
//                        if([cell.nameLabel.text isEqualToString:downloader.downloadModel.videoFileName]) {
//                            if (error) {
//                                cell.sizeLabel.text = error.localizedDescription;
//                                cell.pauseBtn.selected = YES;
//                            }
//                            else {
//                                [cell setModel:downloader];
//                            }
//                        }
                    }
                }
                
            });
        }
        return;
    }
    
    //下载中的错误处理...
    
    //如果下载中出现-1005的错误,是sessiontask返回的错误,可以再次resume来解决下载失败的问题
    if(downloader && downloader.downloadModel.state == PMDownloadState_Failed && downloader.downloadModel.error.code == -1005) {
        if(downloader.downloadModel.downloadFileType == PMDownloadFileType_Video) {
            NSLog(@"start vid:%@", downloader.downloadModel.vid);
            //            [[PMDownloadManager downloadManager] resume:downloader.downloadModel.vid];
        }
        else {
            NSLog(@"start classid:%@", downloader.downloadModel.classId);
            //            [[PMDownloadManager downloadManager] resume:downloader.downloadModel.classId sessionId:downloader.downloadModel.sessionId];
        }
    }
    
    NSLog(@"TableView: downloader.downloadModel.error.description - %@", downloader.downloadModel.error.description);
    NSLog(@"TableView: error %@", error.description);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSArray *cellArr = [self.downloadingTab visibleCells];
        for (id obj in cellArr) {
            if([obj isKindOfClass:[BJYDownlodingCell class]]) {
                BJYDownlodingCell *cell = (BJYDownlodingCell *)obj;
#pragma mark - 设置cell
//                if([cell.nameLabel.text isEqualToString:downloader.downloadModel.videoFileName]) {
//                    if (error) {
//                        cell.sizeLabel.text = error.localizedDescription;
//                        cell.pauseBtn.selected = YES;
//                    }
//                    else {
//                        [cell setModel:downloader];
//                    }
//                }
            }
        }
    });
}


#pragma mark - property
- (UITableView *)downloadingTab{
    if (_downloadingTab == nil) {
        _downloadingTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationBarHeight-36) style:UITableViewStylePlain];
        _downloadingTab.delegate = self;
        _downloadingTab.dataSource = self;
        [_downloadingTab registerClass:[BJYDownlodingCell class] forCellReuseIdentifier:@"BJYDownlodingCell"];
        _downloadingTab.rowHeight = UITableViewAutomaticDimension;
        // 设置tableView的估算高度
        _downloadingTab.estimatedRowHeight = 60;
        _downloadingTab.tableFooterView = [UIView new];
        
    }
    return _downloadingTab;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
